package com.corecmd.tcloud.tcimserver.shiro;

import com.corecmd.tcloud.tcimserver.domain.UserInfoDTO;
import com.corecmd.tcloud.tcimserver.enums.AvailableStatusEnum;
import com.corecmd.tcloud.tcimserver.mapper.IUserMapper;
import com.corecmd.tcloud.tcimserver.utils.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author : tianshaojiao
 * @version : 1.0
 * @apiNote :
 * @date : 2020/6/21
 * @copyright :
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Autowired
    private IUserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("查询授权信息");
        /*UserInfoDTO userInfoBasicDTO = ShiroUtils.getUser();
        String userId = userInfoBasicDTO.getUserId();
        Set<String> perms = null;
        try {
            perms = menuService.listPerms(userId);
        } catch (Exception e) {
            log.info("查询用户["+userId+"]权限异常",e);
        }
        if (null != perms && perms.size() > 0){
            log.info("用户["+userId+"]权限信息为：" + perms.toString());
        }else {
            log.info("没有查到用户["+userId+"]的权限信息");
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(perms);
        log.info("权限信息："+perms.toString());*/
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        CustomUsernamePasswordToken customUsernamePasswordToken = (CustomUsernamePasswordToken)authenticationToken;
        String userId = (String) customUsernamePasswordToken.getPrincipal();
        // 查询用户信息,待实现
        UserInfoDTO loginUser = null;
        loginUser = userMapper.getUserById(Integer.parseInt(userId));
        // 账号不存在
        if (loginUser == null) {
            throw new UnknownAccountException("账号或密码不正确");
        }
        log.info("登录用户信息："+loginUser.toString());
        // 账号锁定
        if (String.valueOf(AvailableStatusEnum.NO.getCode()).equalsIgnoreCase(String.valueOf(loginUser.getStatus()))) {
            throw new LockedAccountException("账号已被锁定,请联系管理员");
        }
        String userPassword = loginUser.getPassword();
        loginUser.setPassword("");
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(loginUser, userPassword, ByteSource.Util.bytes(MD5Utils.SALT), getName());
        return info;
    }
}
